<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { InventoryApi } from '#/models/inventory/inventory';

import { computed, ref, watch } from 'vue';

import { BasicTable } from '@vben/components/table';

import { Col, Row, Tag } from 'ant-design-vue';

import { useVbenModal } from '#/adapter/form';
import { $t } from '#/locales';

// 定义盘点明细项接口
interface CheckItem {
  detail_id: number;
  product_id: number;
  product_code: string;
  product_name: string;
  specification: string;
  unit: string;
  system_quantity: number;
  actual_quantity: number;
  variance_quantity: number;
  variance_amount: number;
  unit_cost: number;
  location_id?: number;
  location_code?: string;
  location_name?: string;
  remark?: string;
  is_deleted: boolean;
  creator?: string;
  update_time?: string;
  create_time?: string;
  updated_by?: string;
}

// 记录数据
const record = ref<InventoryApi.InventoryCheck>();

// 标题
const title = computed(() => $t('inventory.check.detail'));

/**
 * 获取状态名称
 */
function getStatusName(status: string): string {
  const statusMap: Record<string, string> = {
    draft: $t('inventory.check.status.draft'),
    in_progress: $t('inventory.check.status.inProgress'),
    completed: $t('inventory.check.status.completed'),
    closed: $t('inventory.check.status.closed'),
  };
  return statusMap[status] || '-';
}

/**
 * 获取状态颜色
 */
function getStatusColor(status: string): string {
  const colorMap: Record<string, string> = {
    draft: '#d9d9d9',
    in_progress: '#1890ff',
    completed: '#52c41a',
    closed: '#bfbfbf',
  };
  return colorMap[status] || '#d9d9d9';
}

/**
 * 根据差异数量计算状态名称和颜色
 */
function getItemStatus(qty: number): string {
  if (qty === 0) return 'normal';
  return qty < 0 ? 'shortage' : 'excess';
}

function getItemStatusName(qty: number): string {
  const statusMap: Record<string, string> = {
    normal: $t('inventory.check.itemStatus.normal'),
    shortage: $t('inventory.check.itemStatus.shortage'),
    excess: $t('inventory.check.itemStatus.excess'),
  };
  return statusMap[getItemStatus(qty)] || '-';
}

function getItemStatusColor(qty: number): string {
  const colorMap: Record<string, string> = {
    normal: '#52c41a',
    shortage: '#ff4d4f',
    excess: '#fa8c16',
  };
  return colorMap[getItemStatus(qty)] || '#d9d9d9';
}

/**
 * 格式化时间
 */
function formatTime(time?: string): string {
  if (!time) return '-';
  try {
    return new Date(time).toLocaleString('zh-CN');
  } catch {
    return time;
  }
}

/**
 * 格式化数字
 */
function formatNumber(num?: number | string): string {
  if (num === undefined || num === null) return '0';
  return typeof num === 'number' ? num.toFixed(2) : num;
}

/**
 * 格式化差异值
 */
function formatDiff(diff?: number | string): string {
  if (diff === undefined || diff === null) return '0';
  const num = typeof diff === 'number' ? diff : parseFloat(diff);
  return num > 0 ? `+${num.toFixed(2)}` : num.toFixed(2);
}

/**
 * 获取差异值颜色
 */
function getDiffColor(diff?: number | string): string {
  if (diff === undefined || diff === null) return '#333';
  const num = typeof diff === 'number' ? diff : parseFloat(diff);
  return num > 0 ? '#ff4d4f' : num < 0 ? '#52c41a' : '#333';
}

/**
 * 盘点明细列配置
 */
const detailColumns: VxeTableGridOptions<CheckItem>['columns'] = [
  {
    title: $t('inventory.check.detailColumns.productCode'),
    field: 'product_code',
    width: 120,
  },
  {
    title: $t('inventory.check.detailColumns.productName'),
    field: 'product_name',
    width: 180,
  },
  {
    title: $t('inventory.check.detailColumns.specification'),
    field: 'specification',
    width: 150,
  },
  {
    title: $t('inventory.check.detailColumns.unit'),
    field: 'unit',
    width: 80,
  },
  {
    title: $t('inventory.check.detailColumns.unitCost'),
    field: 'unit_cost',
    width: 100,
    formatter: ({ text }) => formatNumber(text),
  },
  {
    title: $t('inventory.check.detailColumns.systemQuantity'),
    field: 'system_quantity',
    width: 100,
  },
  {
    title: $t('inventory.check.detailColumns.actualQuantity'),
    field: 'actual_quantity',
    width: 100,
  },
  {
    title: $t('inventory.check.detailColumns.varianceQuantity'),
    field: 'variance_quantity',
    width: 100,
    formatter: ({ text }) => formatDiff(text),
  },
  {
    title: $t('inventory.check.detailColumns.varianceAmount'),
    field: 'variance_amount',
    width: 120,
    formatter: ({ text }) => `¥${formatDiff(text)}`,
  },
  {
    title: $t('inventory.check.detailColumns.location'),
    field: 'location_name',
    width: 120,
    formatter: ({ row }) => {
      return row.location_name || row.location_code || '-';
    },
  },
  {
    title: $t('system.remark'),
    field: 'remark',
    minWidth: 150,
    ellipsis: true,
  },
];

/**
 * 创建模态框
 */
const [Modal, modalApi] = useVbenModal({
  width: 1000,
  onOpenChange: (isOpen) => {
    if (isOpen) {
      const data = modalApi.getData<InventoryApi.InventoryCheck>();
      if (data) {
        record.value = data;
      }
    }
  },
});

// 监听模态框数据变化
watch(
  () => modalApi.getData<InventoryApi.InventoryCheck>(),
  (newData) => {
    if (newData) {
      record.value = newData;
    }
  },
);
</script>

<template>
  <Modal :title="title">
    <div v-if="record" class="check-detail">
      <!-- 基础信息 -->
      <div class="detail-section">
        <h3 class="section-title">{{ $t('inventory.check.basicInfo') }}</h3>
        <Row :gutter="[16, 16]">
          <Col :span="12">
            <div class="detail-row">
              <span class="detail-label"
                >{{ $t('inventory.check.code') }}:</span
              >
              <span class="detail-value">{{ record.check_code }}</span>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-row">
              <span class="detail-label"
                >{{ $t('inventory.check.status') }}:</span
              >
              <Tag :color="getStatusColor(record.status)">
                {{ getStatusName(record.status) }}
              </Tag>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-row">
              <span class="detail-label"
                >{{ $t('inventory.warehouse.name') }}:</span
              >
              <span class="detail-value">{{
                record.warehouse?.warehouse_name || '-'
              }}</span>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-row">
              <span class="detail-label"
                >{{ $t('inventory.check.date') }}:</span
              >
              <span class="detail-value">{{ record.check_date }}</span>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-row">
              <span class="detail-label"
                >{{ $t('inventory.check.checker') }}:</span
              >
              <span class="detail-value">{{ record.checker_id }}</span>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-row">
              <span class="detail-label"
                >{{ $t('inventory.check.approver') }}:</span
              >
              <span class="detail-value">{{ record.approver_id || '-' }}</span>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-row">
              <span class="detail-label">{{ $t('system.createTime') }}:</span>
              <span class="detail-value">{{
                formatTime(record.create_time)
              }}</span>
            </div>
          </Col>
          <Col :span="12">
            <div class="detail-row">
              <span class="detail-label"
                >{{ $t('inventory.check.completeTime') }}:</span
              >
              <span class="detail-value">{{
                formatTime(record.end_time)
              }}</span>
            </div>
          </Col>
          <Col :span="24">
            <div class="detail-row">
              <span class="detail-label">{{ $t('system.remark') }}:</span>
              <span class="detail-value">{{ record.remark || '-' }}</span>
            </div>
          </Col>
        </Row>
      </div>

      <!-- 盘点结果统计 -->
      <div class="detail-section">
        <h3 class="section-title">{{ $t('inventory.check.resultStats') }}</h3>
        <div class="stat-cards">
          <div class="stat-card">
            <div class="stat-value">{{ record.details?.length || 0 }}</div>
            <div class="stat-label">
              {{ $t('inventory.check.productCount') }}
            </div>
          </div>
          <div class="stat-card">
            <div
              class="stat-value"
              :class="{ diff: Math.abs(record.total_variance_amount || 0) > 0 }"
            >
              ¥{{ formatNumber(record.total_variance_amount || 0) }}
            </div>
            <div class="stat-label">
              {{ $t('inventory.check.totalDiffAmount') }}
            </div>
          </div>
        </div>
      </div>

      <!-- 盘点明细 -->
      <div class="detail-section">
        <h3 class="section-title">{{ $t('inventory.check.items') }}</h3>
        <BasicTable
          :columns="detailColumns"
          :data-source="record.details || []"
          :pagination="{ pageSize: 10, showSizeChanger: true }"
          :scroll="{ x: 800 }"
        >
          <template #system_quantity="{ text }">
            <span>{{ formatNumber(text) }}</span>
          </template>
          <template #actual_quantity="{ text }">
            <span>{{ formatNumber(text) }}</span>
          </template>
          <template #variance_quantity="{ text }">
            <span :style="{ color: getDiffColor(text) }">
              {{ formatDiff(text) }}
            </span>
          </template>
          <template #variance_amount="{ text }">
            <span :style="{ color: getDiffColor(text) }">
              {{ formatDiff(text) }}
            </span>
          </template>
        </BasicTable>
      </div>
    </div>
  </Modal>
</template>

<style lang="css" scoped>
.check-detail {
  padding: 20px 0;
}

.detail-section {
  margin-bottom: 24px;
}

.section-title {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 500;
  color: rgb(0 0 0 / 85%);
}

.detail-row {
  margin-bottom: 12px;
}

.detail-label {
  display: inline-block;
  width: 100px;
  color: rgb(0 0 0 / 45%);
}

.detail-value {
  color: rgb(0 0 0 / 85%);
}

.stat-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.stat-card {
  flex: 1;
  min-width: 160px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.stat-value {
  margin-bottom: 4px;
  font-size: 24px;
  font-weight: 500;
  color: rgb(0 0 0 / 85%);
}

.stat-value.diff {
  font-weight: 600;
  color: #ff4d4f;
}

.stat-label {
  color: rgb(0 0 0 / 45%);
}
</style>
